package com.media.appmedia.fragment;

import java.util.ArrayList;

import net.miidiwall.SDK.AdWall;
import net.miidiwall.SDK.IAdWallGetPointsNotifier;
import net.miidiwall.SDK.IAdWallShowAppsNotifier;
import net.miidiwall.SDK.IAdWallSpendPointsNotifier;
import net.youmi.android.AdManager;
import net.youmi.android.offers.OffersManager;
import net.youmi.android.offers.PointsManager;

import org.json.JSONArray;
import org.json.JSONException;

import cn.dm.android.DMOfferWall;
import cn.dm.android.listener.CheckPointListener;
import cn.dm.android.model.ErrorInfo;
import cn.dm.android.model.Point;
import cn.guomob.android.intwal.OpenIntegralWall;
import cn.waps.AppConnect;
import cn.waps.UpdatePointsNotifier;

import com.ad.creditswall.view.CreditsWall;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.media.appmedia.R;
import com.media.appmedia.adapter.WallAdapter;
import com.media.appmedia.entity.UserGradeInfo;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;
import com.zkmm.appoffer.OfferListener;
import com.zkmm.appoffer.ZkmmAppOffer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Make_Money_Childer1 extends Fragment implements
		IAdWallGetPointsNotifier, IAdWallSpendPointsNotifier,
		IAdWallShowAppsNotifier, OfferListener {
	private ArrayList<String> wallList;
	// 安沃
	private ZkmmAppOffer mAppOffer;
	@ViewInject(R.id.wall_list)
	private ListView listView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View mView = inflater.inflate(R.layout.makefragment1, null);
		ViewUtils.inject(this, mView);
		initView();
		setListView();
		// 初始化积分墙
		initWall();
		return mView;
	}

	/**
	 * 
	 * 方法说明：初始化积分墙
	 * 
	 */
	private void initWall() {
		// 万普96ZJ34nQzeeEbwTBbl
		AppConnect.getInstance("2c9a05e6dc1383ea4a0a305bb052fd0e", "default",
				getActivity());
		// 多盟
		DMOfferWall.init(getActivity(), "96ZJ34nQzeeEbwTBbl");
		// 米迪
		AdWall.setUserActivity(getActivity(),
				"com.media.appmedia.activity.UserActivity");
		AdWall.init(getActivity(), "20089", "wui3wqeiqw0q0twc");
		// 有米
		// 初始化接口，应用启动的时候调用，参数：appId, appSecret, 是否开启调试模式
		AdManager.getInstance(getActivity()).init("e98cc4c473be5096 ",
				"3682670ff7e6b650", false);
		OffersManager.getInstance(getActivity()).setCustomUserId(
				PhoneInfoUtils.getIMEI(getActivity()));
		OffersManager.setUsingServerCallBack(true);
		// 安沃
		// 初始化接口，应用启动的时候调用，参数：appId, appSecret, 是否开启调试模式
		mAppOffer = ZkmmAppOffer.getInstance(getActivity(),
				"08493f1dadbf4b31a44a1d465f5f1e05");
		// 果盟
		OpenIntegralWall.getInstance();
		OpenIntegralWall.init(getActivity());
	}

	private void setListView() {
		// 下载适配
		wallList = new ArrayList<String>();
		getMake();

	}

	private void initView() {
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int postion, long arg3) {
				String wall_name = wallList.get(postion);
				if ("果盟".equals(wall_name)) {
					OpenIntegralWall openIntegralWall = OpenIntegralWall
							.getInstance();
					openIntegralWall.show();
				} else if ("万普".equals(wall_name)) {
					AppConnect.getInstance(getActivity()).showOffers(
							getActivity());
				} else if ("多盟".equals(wall_name)) {
					DMOfferWall.getInstance(getActivity()).showOfferWall(
							getActivity());
				} else if ("米迪".equals(wall_name)) {
					AdWall.showAppOffers(Make_Money_Childer1.this);
					System.out.println("");
				} else if ("有米".equals(wall_name)) {
					OffersManager.getInstance(getActivity()).showOffersWall();
				} else if ("安沃".equals(wall_name)) {
					mAppOffer.showOffer(getActivity());
				}
			}
		});

	}

	@Override
	public void onDismissApps() {
		Log.d("AdWall", "关闭积分墙的Activity");
	}

	@Override
	public void onShowApps() {
		Log.d("AdWall", "开始显示积分墙的Activity");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.zkmm.appoffer.OfferListener#onReceiveAd() 积分墙初始化成功回调接口
	 */
	@Override
	public void onReceiveAd() {
		Toast.makeText(getActivity(), "积分墙初始化成功!", Toast.LENGTH_SHORT).show();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.zkmm.appoffer.OfferListener#onFailedToReceiveAd() 积分墙初始化失败回调接口
	 */
	@Override
	public void onFailedToReceiveAd() {
		Toast.makeText(getActivity(), "积分墙初始化不成功,有可能是由于请求频繁，请稍候再次请求。",
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 重新回到该界面时进行积分再次统计
	 */

	@Override
	public void onStart() {
		super.onStart();
		// 万普
		// AppConnect.getInstance(getActivity()).getPoints(this);
		// 安沃-------->
//		setGoldA();
		// 多盟
		// setGoldD();
		// 米迪
		// AdWall.getPoints(this);
		// 有米
//		setGoldY();
		// 巴依老爷------>
		// setGoldB();
	}

	@Override
	public void onDestroy() {

		// 释放资源，原finalize()方法名修改为close() 万普
		AppConnect.getInstance(getActivity()).close();
		// 销毁夹在进度条对话框，因为在跳出当前activity是如果不再这里调用销毁进度条，会导致对话框失去附属activity。
		if (mAppOffer != null) {
			mAppOffer.dismissProgressDialog();
		}
		OpenIntegralWall.getInstance().onUnbind();
		super.onDestroy();
	}

	/**
	 * 
	 * 方法说明：上传服务器数据(获得金币)
	 * 
	 * @param name
	 * @param content
	 * @param numb
	 */
	private void setGold(String name, String content, int numb) {
		ProtocolService.setGolds(PhoneInfoUtils.getIMEI(getActivity()), name,
				content, numb, new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						System.out.println();
						UserGradeInfo info = JSONObject.parseObject(
								arg0.result, UserGradeInfo.class);
						if (info.getMessage() == 1) {
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getActivity().getApplicationContext(),
								R.string.phone_verify_send_fail);
					}
				});
	}

	/**
	 * 
	 * 方法说明：安沃上传金币方法封装
	 * 
	 */
	private void setGoldA() {
		if (mAppOffer == null) {

			return;
		}
		int goldA = mAppOffer.getTotalOfferVirtualCurrency(getActivity());
		if (goldA > 0) {
			setGold("安沃", "下载任务", goldA);
			mAppOffer.consumeVirtualCurrency(getActivity(), goldA);
		}
	}

	/**
	 * 
	 * 方法说明：多盟上传金币
	 * 
	 */
	private void setGoldD() {
		DMOfferWall.getInstance(getActivity()).checkPoints(
				new CheckPointListener() {
					@Override
					public void onError(ErrorInfo errorInfo) {
					}

					@Override
					public void onResponse(Point data) {
						int gold = data.point - data.consumed;
						if (gold > 0) {
							// setGold("多盟", "下载任务", gold);
							DMOfferWall.getInstance(getActivity())
									.consumePoints(gold,
											new CheckPointListener() {
												@Override
												public void onError(
														ErrorInfo errorInfo) {
												}

												@Override
												public void onResponse(
														Point data) {

													System.out.println("");
												}
											});

						}
					}
				});
	}

	/**
	 * 切换回调接口进行金币添加
	 */
	@Override
	public void onStop() {
		super.onStop();
	}

	// 米迪获取积分回调接口
	/**
	 * 米迪上传金币接口
	 */
	@Override
	public void onFailReceivePoints() {
	}

	@Override
	public void onReceivePoints(String arg0, Integer arg1) {
		if (arg1 > 0) {
			// setGold("米迪", "下载任务", arg1);
			// 消费全部积分
			AdWall.spendPoints(arg1, this);
		}
		System.out.println("");
	}

	@Override
	public void onFailSpendPoints() {
		System.out.println();
	}

	@Override
	public void onSpendPoints(String arg0, Integer arg1) {
		// 米迪消费成功，不做处理
		System.out.println("是否全部消费成功？");
	}

	private void setGoldY() {
		int goldY = PointsManager.getInstance(getActivity()).queryPoints();
		if (goldY > 0) {
			setGold("有米", "下载任务", goldY);
			// 消费全部积分
			boolean isSuccess = PointsManager.getInstance(getActivity())
					.spendPoints(goldY);
			System.out.println("");
		}
	}

	// private void setGoldB() {
	// int goldB = CreditsWall.getInstance().getCredits(getActivity())
	// .getNum();
	// if (goldB > 0) {
	// setGold("巴依", "下载任务", goldB);
	// // 消费全部积分
	// CreditsWall.getInstance().spendCredits(getActivity(), goldB);
	// }
	// }

	private void getMake() {
		ProtocolService.getMakes(PhoneInfoUtils.getIMEI(getActivity()),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							if (obj.getInt("message") == 1) {
								JSONArray array = obj.getJSONArray("0");
								for (int i = 0; i < array.length(); i++) {
									org.json.JSONObject obj2 = array
											.getJSONObject(i);
									wallList.add(getName(obj2
											.getString("integral_wall_num")));
								}
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}

						WallAdapter adapter = new WallAdapter(wallList,
								getActivity());
						listView.setAdapter(adapter);
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}
				});
	}

	private String getName(String type) {
		String name = null;
		if ("8".equals(type)) {
			name = "果盟";
		} else if ("9".equals(type)) {
			name = "多盟";
		} else if ("10".equals(type)) {
			name = "万普";
		} else if ("11".equals(type)) {
			name = "米迪";
		} else if ("12".equals(type)) {
			name = "有米";
		} else if ("13".equals(type)) {
			name = "安沃";
		}
		return name;

	}
}
